﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using LitJson;
using System.Text;
using System.Net;

public class NetManager : MonoBehaviour
{
    private const bool Log_Enable = true;

    private static NetManager m_Inst;
    public static NetManager Instance
    {
        get { return m_Inst; }
    }

    private Queue<SocketHelper.ThreadMessage> m_ThreadMessageQueue = new Queue<SocketHelper.ThreadMessage>();

    private MyUdpServerConn m_Server1;
    private MyUdpClientConn m_Client1;

    public NetManager()
    {
        if (null == m_Inst)
            m_Inst = this;
        else
            Debug.LogError($"multi Instance");
    }

    void OnDestroy()
    {
        if (this == m_Inst) m_Inst = null;

        m_Server1.Stop();
        m_Client1.Stop();
    }

    void Start()
    {
        m_Server1 = new MyUdpServerConn("server1", m_ThreadMessageQueue);
        m_Server1.m_BindPort = 8081;
        m_Server1.Start();

        m_Client1 = new MyUdpClientConn("client1", m_ThreadMessageQueue);
        m_Client1.m_BindPort = 8082;
        m_Client1.SetServerAddress(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081));
        m_Client1.Start();
    }

    //******************** 消息队列(渲染线程转发)

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            m_Client1.Send("测试client1消息");
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            
        }

        CheckThreadMessageQueue();
    }

    private void CheckThreadMessageQueue()
    {
        if (m_ThreadMessageQueue.Count > 0)
        {
            lock (m_ThreadMessageQueue)
            {
                while (m_ThreadMessageQueue.Count > 0)
                {
                    var cmd = m_ThreadMessageQueue.Dequeue();
                    OnThreadMessage(cmd);
                }
            }
        }
    }

    //********************

    //渲染线程上执行
    private void OnThreadMessage(SocketHelper.ThreadMessage msg)
    {
        if (Log_Enable) Debug.Log($"server: OnThreadMessage: {msg.m_Cmd}");

        switch (msg.m_Cmd)
        {
        }
    }

}
